package com.cz.spb_activiti.controller;

import com.alibaba.fastjson2.JSONObject;
import com.cz.spb_activiti.mapper.DemandMapper;
import com.cz.spb_activiti.mapper.UserMapper;
import com.cz.spb_activiti.pojo.Demand;
import com.cz.spb_activiti.pojo.User;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("demand")
public class DemandActivitiController {
    Logger logger= LoggerFactory.getLogger(DemandActivitiController.class);

    @Autowired
    RepositoryService repositoryService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;

    @Autowired
    DemandMapper demandMapper;

    @Autowired
    UserMapper userMapper;

    /*测试数据
    http://localhost:8080/test/demand/createDemand
    * {
            "id": "demand001",
            "name": "架构单体架构转为微服务",
            "content": "一个个来",
            "taskId": "task001",
            "createUser": {"username":"climber"}
    }
    * */
    @PostMapping("createDemand")
    public String  createDemand(@RequestBody Demand demand) {
        User createUser = userMapper.selectById(demand.getApplicantId());
        //设置发起人
        Authentication.setAuthenticatedUserId(createUser.getUsername());
        //查询发起人对应的组长，假设为 Lisa 分配处理人
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("groupLeader", "Lisa");
//        ProcessInstanceKey 位于流程定义文件中 <process id="demand"
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("demand", demand.getName() , variables);
        demand.setProcessInstanceId(processInstance.getProcessInstanceId());
        demandMapper.insert(demand);

        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();

        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("msg", "需求提交成功");
//        objectObjectHashMap.put("detail", processInstances);
        for (ProcessInstance instance : processInstances) {
            logger.info(instance.toString());
        }
        return new JSONObject(objectObjectHashMap).toJSONString();


    }

    /*
    * 测试数据
    *
    * 组长审核 http://localhost:8080/test/demand/handleTask?leader=Lisa&opinion=1
    *
    * 经理 http://localhost:8080/test/demand/handleTask?leader=xiaoxiao&opinion=1
    *
    * */
    @GetMapping("handleTask")
    public String handleTask(String leader,String opinion) {
        logger.info("receive opinion is" + opinion);
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(leader).list();
        if (null == tasks || tasks.size() == 0) {
            return "无需要" + leader + "处理的任务";
        } else {

            //此时可以先设置好下个节点 这个leaderUser就是你在流程节点里面设置的接收参数
            HashMap<String, Object> variable = new HashMap<>();
        // 身份查询 与 流程身份判断 ，如何是该流程线最后一个节点，那就不需要设置后续节点办理人
            if ("Lisa".equals(leader)){
                variable.put("manager", "xiaoxiao");
            }
//            variable.put("opinion",opinion);
            HashMap<String, Object> map = new HashMap<>();
            for (Task task : tasks) {
                logger.info("ready to process " + task.getBusinessKey());

                Authentication.setAuthenticatedUserId(leader); // 添加批注时候的审核人，通常应该从session获取

                taskService.addComment(task.getId(),task.getProcessInstanceId(),opinion.equals("1")?"同意":"反对");
                taskService.setVariable(task.getId(),"opinion",opinion);
                taskService.complete(task.getId(), variable);
                map.put(task.getName(), opinion.equals("1")?"同意":"反对");
            }
            return new JSONObject(map).toJSONString();
        }

    }



}
